package com.usermanage.servlet.filter;
/**
 * 字符过滤器，修改编码格式
 */



import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class CharactorFilter
 */
@WebFilter("/*")
public class CharactorFilter implements Filter {

    /**
     * Default constructor. 
     */
    public CharactorFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		//设置而响应的编码和内容类型
		response.setContentType("text/html;charset=utf-8");
		
		//将请求对象转换为子类对象
		HttpServletRequest request2=(HttpServletRequest) request;
		
		//获得请求的方式
		String method=request2.getMethod();
		if ("get".equalsIgnoreCase(method)) {//处理get请求乱码
			//用装饰者模式将原来请求对象装饰，重写请求中获得请求中的数据的方法
			MyRequest mr=new MyRequest(request2);
			chain.doFilter(mr, response);
		}else {
			request2.setCharacterEncoding("utf-8");
			chain.doFilter(request2, response);
		}
		
	}
	/**
	 * 请求对象装饰者类
	 * 重写获得请求中数据的方法，对请求中值进行重新编码
	 * @author 陆贝伊
	 *
	 */
	class MyRequest extends HttpServletRequestWrapper{
		HttpServletRequest request3;
		public MyRequest(HttpServletRequest request) {
			super(request);
			this.request3=request;
		}
		//重写父类中获得单个值的方法
		@Override
		public String getParameter(String name) {
			//获得值
			String value=super.getParameter(name);
			if (value!=null&&value.length()!=0) {
				try {
					value=new String(value.getBytes("ISO-8859-1"),"UTF-8");

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return value;
		}
		/**
		 * 重写父类中获得一组值的方法
		 */
		@Override
		public String[] getParameterValues(String name) {
			//获得一组值
			String[] values=super.getParameterValues(name);
			if (values!=null) {
				for (int i = 0; i < values.length; i++) {
					try {
						values[i]=new String(values[i].getBytes("ISO-8859-1"),"utf-8");
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
			return values;
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
